package com.cloud.clouduser.security.base.code.imagecode;

import com.cloud.clouduser.security.base.SecurityPorperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @Aurher: QiaoHang
 * @Description:
 * @Data: 2019/9/26 16:03
 * @Modified By:
 */
//默认的生成图像验证码的组件
//在用户没有定义相同共嗯那个的组件时生效
public class CommonImageCodeGenerator implements ImageCodeGenerator, CommandLineRunner {

    @Autowired
    private SecurityPorperties securityPorperties;
    // ********************图形验证码的字符集合，系统将随机从这个字符串中选择一些字符作为验证码
    private static String codeChars = null;
    // ********************image验证码的可用时间
    private static int userAbleTime;

    @Override
    public void run(String... args) throws Exception {
        codeChars = securityPorperties.getValidate().getImage().getCodeChars();
        userAbleTime = securityPorperties.getValidate().getImage().getUserAbleTime();
    }

    /**
     * 创建图片二维码
     * @return
     */
    @Override
    public ImageCode createImageCode(HttpServletRequest request) {
        StringBuffer validationCode = new StringBuffer();
        // 获得验证码集合的长度
        int charsLength = codeChars.length();
        // *******************设置图形验证码的长和宽（图形的大小）  request > definedConfig > defaultConfig
        int width = ServletRequestUtils.getIntParameter(request,"width",securityPorperties.getValidate().getImage().getWidth());
        int height = ServletRequestUtils.getIntParameter(request,"width",securityPorperties.getValidate().getImage().getHeight());
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获得用于输出文字的Graphics对象
        Graphics g = image.getGraphics();
        Random random = new Random();
        // 随机设置要填充的颜色
        g.setColor(getRandomColor(80, 250));
        // 填充图形背景
        g.fillRect(0, 0, width, height);
        // 设置初始字体
        g.setFont(new Font("Times New Roman", Font.ITALIC, height));
        // 随机设置字体颜色
        g.setColor(getRandomColor(120, 180));
        // 验证码的随机字体
        String[] fontNames = { "Times New Roman", "Book antiqua", "Arial" };
        // *****************随机生成n个验证码   request > definedConfig > defaultConfig
        int charLength = ServletRequestUtils.getIntParameter(request,"charLength",securityPorperties.getValidate().getImage().getCharLength());
        for (int i = 0; i < charLength; i++) {
            // 随机设置当前验证码的字符的字体
            g.setFont(new Font(fontNames[random.nextInt(3)], Font.ITALIC, height));
            // 随机获得当前验证码的字符
            char codeChar = codeChars.charAt(random.nextInt(charsLength));
            validationCode.append(codeChar);
            // 随机设置当前验证码字符的颜色
            g.setColor(getRandomColor(10, 100));
            // 在图形上输出验证码字符，x和y都是随机生成的
            g.drawString(String.valueOf(codeChar), 16 * i + random.nextInt(7), height - random.nextInt(6));
        }
        // 关闭Graphics对象
        g.dispose();
        ImageCode myInageCode = new ImageCode(validationCode.toString(),image,userAbleTime);
        // 输出验证码
        System.out.println("本次生成的验明码："+ validationCode);
        return myInageCode;
    }


    /**
     * 返回一个随机颜色(Color对象)
     * @param minColor
     * @param maxColor
     * @return
     */
    private static Color getRandomColor(int minColor, int maxColor) {
        Random random = new Random();
        // 保存minColor最大不会超过255
        if (minColor > 255)
            minColor = 255;
        // 保存minColor最大不会超过255
        if (maxColor > 255)
            maxColor = 255;
        // 获得红色的随机颜色值
        int red = minColor + random.nextInt(maxColor - minColor);
        // 获得绿色的随机颜色值
        int green = minColor + random.nextInt(maxColor - minColor);
        // 获得蓝色的随机颜色值
        int blue = minColor + random.nextInt(maxColor - minColor);
        return new Color(red, green, blue);
    }

}
